#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include "queue.h"

//入队
queue *queueInsert(queue *headque, int serialNo, int length, char *data) {
    // 1. 定义变量
    node *s = NULL;

    // 2. 新建节点
    s = (node *)malloc(sizeof(node));
    s->serialNo = serialNo;
    s->length = length;
    char *cData = (char *)calloc(length, sizeof(char));
    memcpy(cData, data, length);
    s->data = cData;
    s->insertTime = time(NULL);
    s->next = NULL;

    // 3. 插入队尾
    if (headque->rear == NULL) //第一个节点
    {
        s->pre = NULL;
        headque->first = s;
        headque->rear = s;
    }
    else {
        s->pre = headque->rear;
        headque->rear->next = s;
        headque->rear = s;
    }

    // 4. 返回队列
    return headque;
}

//出队
node *queuePop(queue *headque) {
    // 1. 定义变量
    node *p = NULL;
    int x = 0;

    // 2. 节点出队
    if (headque->first == NULL) //队列为空
    {
        // printf("队列为空\n");
    }
    else {
        p = headque->first;
        if (headque->first == headque->rear) //到达队尾
        {
            headque->first = NULL;
            headque->rear = NULL;
        }
        else //删除节点
        {
            headque->first = headque->first->next;
            // free(p);
            // p = NULL;
        }

        // 4. 返回队列
        // return headque;
    }
    return p;
}

node *getTargetNodeInQueue(queue *headque, int serialNo) {
    // 1. 定义变量
    node *p = NULL;
    int x = 0;

    // 2. 遍历显示
    p = headque->first;
    while (p != NULL) {
        if (p->serialNo == serialNo) {
            return p;
        }
        p = p->next;
    }
    return NULL;
}

int removeTargetNodeQueue(queue *headque, int serialNo) {
    int ret = 0;
    // 1. 定义变量
    node *p = NULL;
    int x = 0;

    // 2. 遍历
    p = headque->first;
    while (p != NULL) {
        if (p->serialNo == serialNo) {
            //找到目标
            if (p->pre == NULL) {
                //如果前面无
                if (p->next == NULL) {
                    headque->first = NULL;
                    headque->rear = NULL;
                }
                else {
                    p->next->pre = NULL;
                    headque->first = p->next;
                }
            }
            else {

                if (p->next == NULL) {
                    p->pre->next = NULL;
                    headque->rear = NULL;
                }
                else {
                    p->pre->next = p->next;
                    p->next->pre = p->pre;
                }
            }
            // show(headque);
            ret = 1;
            break;
        }
        p = p->next;
    }
    return ret;
}

//显示队列所有节点信息
void show(queue *headque) {
    // 1. 定义变量
    node *p = NULL;
    int x = 0;
    printf("当前队列中的数据有：\n");
    // 2. 遍历显示
    p = headque->first;
    while (p != NULL) {
        // x = p->data;
        printf("sq->:%d\n", p->serialNo);
        p = p->next;
    }
    printf("\n");
}